package ssq.gamest.toolchain;

import java.io.File;
import java.util.Iterator;
import java.util.Set;

import net.sf.json.JSONObject;
import ssq.utils.DirUtils;
import ssq.utils.FileUtils;

public class Generator
{
    public static void main(String[] args)
    {
        File rulesDir = new File(DirUtils.getXxRoot("assets/rules"));
        Set<String> rules = FileUtils.getListOf(rulesDir, true);

        for (Iterator<String> iterator = rules.iterator(); iterator.hasNext();)
        {
            String string = iterator.next();

            File ruleFile = new File(rulesDir, string);

            parse(ruleFile);
        }
    }

    static void parse(File ruleFile)
    {
        String ruleString = FileUtils.fileToString(ruleFile);
        JSONObject jsonObject = JSONObject.fromObject(ruleString);
        jsonObject.put("name", FileUtils.getNameWithoutExt(ruleFile.getName()));
        JSONObject basic = jsonObject.getJSONObject("basic");

        switch ((String) basic.get("type"))
        {
            case "Poker":
                parsePoker(jsonObject);
                break;

            default:
                break;
        }
    }

    private static void parsePoker(JSONObject jsonObject)
    {
        JSONObject basic = jsonObject.getJSONObject("basic"), rule = jsonObject.getJSONObject("rule"), ui = jsonObject.getJSONObject("ui"), ai = jsonObject.getJSONObject("ai");
        GeneratorSettings settings = new GeneratorSettings();
        settings.genDir = "D:/projects/android/Gamest/Server/ports/Windows/src/ssq/gamest/game/";
        settings.gameName = jsonObject.getString("name");

        genDetecter(rule, settings);

        genAI(ai, settings);
    }

    protected static void genAI(JSONObject ai, GeneratorSettings settings)
    {
        AIGenerator aiGenerator = new AIGenerator(settings);
        String expr;
        try
        {
            expr = ai.getString("weight");
        }
        catch (Exception e)
        {
            expr = "sum/(hands+1)/(residual+1)";
        }

        aiGenerator.run(expr);
    }

    protected static void genDetecter(JSONObject rule, GeneratorSettings settings)
    {
        PokerPatternDetecterGenerator pokerPatternDetecterGenerator = new PokerPatternDetecterGenerator(settings);
        JSONObject pattern = rule.getJSONObject("pattern");

        for (Object keyString : pattern.keySet())
        {
            String key = (String) keyString, nameString = key;
            boolean maskable = key.endsWith("*");

            if (maskable)
            {
                nameString = key.substring(0, key.length() - 1);
            }

            pokerPatternDetecterGenerator.run(nameString, pattern.getString(key));
        }
    }
}
